
package org.ezplatform.office.forum.service;

import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.office.forum.dao.ForumPostStatisticsDao;
import org.ezplatform.office.forum.entity.ForumPost;
import org.ezplatform.office.forum.entity.ForumPostStatistics;
import org.ezplatform.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  论坛动态service
 * 2019年11月2日17:40:59
 * @author Administrator
 *
 */
@Service
@Transactional
public class ForumPostStatisticsService extends BaseService<ForumPostStatistics, String> {
	private final Logger LOGGER = LoggerFactory.getLogger(ForumPostService.class);

	@Autowired
	private ForumPostStatisticsDao forumPostStatisticsDao;

	@Lazy
	@Autowired
	private ForumPostService forumPostService;
	
	@Override
	protected JpaBaseDao<ForumPostStatistics, String> getEntityDao() {
		return forumPostStatisticsDao;
	}
	
	public ForumPostStatistics findOneByPostid(String postId){
		return this.findByProperty("postId", postId);
	}
	
	public ForumPostStatistics initStatistics(String postid){
		ForumPostStatistics s = new ForumPostStatistics();
		s.setPostId(postid);
		return s;
	}

	public void initStatisticsRecord(String postid){
		LOGGER.info("开始初始化帖子statistics");
		ForumPostStatistics s = findOneByPostid(postid);
		if(null == s){
			s = initStatistics(postid);
			this.save(s);
		}
		LOGGER.info("结束初始化帖子statistics");
	}

	@Async
	public void autoStatisticsRecord(ForumPost post){
		WebUser user = WebUtils.getCurrentUser();
		
			if(post.getType() == ForumPostService.POST_TYPE_NEW){
				// 帖子
				initStatisticsRecord(post.getId());
			} else {
				// 回帖
				addReplyCount(post.getCreatedBy(), post.getId(), post.getPostId(), post.getCreatedDate());
			}
	}
	
	/**
	 * 
	 * @Title: addReplyCount
	 * @Description:
	 *     添加回帖记录
	 * @param replyId
	 * @param postId 
	 * @param date 
	 * @return: void
	 *
	 * @date 2017年11月27日 下午6:54:59
	 *
	 */
	public void addReplyCount(String userid, String replyId, String postId, Date date){
		LOGGER.info("开始更新帖子回复数");
		ForumPostStatistics s;
		if(StringUtils.isNotBlank(postId)){
			s = this.findOneByPostid(postId);
			if(null == s){
				s = initStatistics(postId);
			}
			s.setReplyCount(s.getReplyCount()+1);
			if(null == s.getLastReplyDate() || s.getLastReplyDate().compareTo(date) <= 0 ) {
				s.setLastReplyId(replyId);
				s.setLastReplyDate(date);
				s.setLastReplyUser(userid);
			}
			s=this.save(s);
		}
		LOGGER.info("结束更新帖子回复数");
		
	}

	/**
	 *
	 * @Title: addReplyCount
	 * @Description:
	 *     (异步)添加查看记录----一个用户只统计一次
	 * @param user
	 * @param postid
	 * @return: void
	 *
	 * @date 2017年11月27日 下午6:54:59
	 *
	 */
	@Async
	public void addViewCount(WebUser user, String postid){
		LOGGER.info("开始更新帖子浏览量");
		if(StringUtils.isNotBlank(postid)){
			ForumPostStatistics s = this.findOneByPostid(postid);
			if(null == s){
				s = initStatistics(postid);
			}
			s.setViewCount(s.getViewCount()+1);
			this.save(s);
			ForumPost p = forumPostService.findOne(postid);
			forumPostService.AllSearch(p, user, false,String.valueOf(s.getViewCount()+1));
			LOGGER.info("帖子浏览量：用户  "+user.getUserName()+"查看帖子"+postid);
		} else {
			LOGGER.info("帖子浏览量：该帖子不存在");
		}
		LOGGER.info("结束更新帖子浏览量");
	}

	/**
	 *
	 * @Title: addReplyCount
	 * @Description:
	 *     删除一个帖子的statistics记录
	 * @param id
	 * @return: void
	 *
	 * @date 2017年11月27日 下午6:54:59
	 *
	 */
	public void deleteStatistics(Object id) {
		String s = " DELETE FROM oa_forum_post_statistics where post_id = ?1 ";
		this.getEntityManager().createNativeQuery(s).setParameter(1, id).executeUpdate();
	}

	/**
	 *
	 * @Title: addReplyCount
	 * @Description:
	 *     减少一个帖子的回帖数
	 * @param post_id
	 * @return: void
	 * @throws ParseException 
	 *
	 * @date 2017年11月27日 下午6:54:59
	 *
	 */
	@Async
	public void subtractReplyCount(Object post_id) throws ParseException {
		if( null != post_id) {
			ForumPostStatistics statistics = this.findByProperty("postId", post_id);
			// 重新计算最后回帖信息;
			List<ForumPost> fplist = forumPostService.getReplyByPostid(post_id.toString(), 2);
			if (!CollectionUtils.isEmpty(fplist)) {
				for (ForumPost p : fplist) {
					if (null != p) {
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String time = sdf.format(p.getCreatedDate());
						statistics.setLastReplyDate(sdf.parse(time));
						statistics.setLastReplyId(p.getId());
						statistics.setLastReplyUser(p.getCreatedBy());
						break;
					}
				}
			} else {
				statistics.setLastReplyDate(null);
				statistics.setLastReplyId("");
				statistics.setLastReplyUser("");
			}

			if (statistics.getReplyCount() > 0) {
				statistics.setReplyCount(statistics.getReplyCount() - 1);
			}
			this.save(statistics);
		}
	}

	public String getCounts(String id, String corpId) {
		ForumPostStatistics forumPostStatistics = forumPostStatisticsDao.getCounts(id,corpId);
		if(forumPostStatistics!=null) {
			return String.valueOf(forumPostStatistics.getViewCount());
		}else {
			return "0";
		}
		// TODO Auto-generated method stub
		
	}

	/**
	 * 通过版块id,获取版块下所有帖子的阅读量和回帖量
	 * @param id
	 * @return
	 */
	public Map findOneByBoardId(String id) {
		String corpId = WebUtils.getCurrentUser().getCorpId();
		StringBuffer sql = new StringBuffer();
		sql.append(" select sum(s.view_count) as viewCount,sum(s.reply_count) as replyCount ");
		sql.append(" from oa_forum_post_statistics s ");
		sql.append(" left join oa_forum_post p on p.id = s.post_id ");
		sql.append(" where p.corp_id = :corpId and p.board_id = :id and p.is_delete = '0' ");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("corpId", corpId);
		paramMap.put("id", id);
		List<Map> result = super.findByListNativeQuery(sql.toString(), null, paramMap);
		if(result!=null&&result.size()>0) {
			return result.get(0);
		}else {
			return new HashMap<>();
		}
			
	}
}
